﻿var map;
var infoWin;
var polygon = new Array();
var polygon_new = null;
$(function(){
    //加载地图
    mapShow();
    treeEvent();
});
function mapShow() {
    //初始化地图
    map = new BMap.Map("map");
    map.centerAndZoom(new BMap.Point(120.523039,36.193397), 14);
    map.addControl(new BMap.MapTypeControl({
        mapTypes:[
            BMAP_NORMAL_MAP,
            BMAP_SATELLITE_MAP,
            BMAP_HYBRID_MAP
        ]}));   //添加地图类型控件
    map.setCurrentCity("青岛市");          // 设置地图显示的城市 此项是必须设置的
    map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放

    //创建右键菜单
    var menu = new BMap.ContextMenu();
    var txtMenuItem = [{
        text: '新增网格区域',
        isDisable: false,
        callback: function (e) {
            addGrid("add",e.lng+','+e.lat);
        }
    }, {
        text: '保存绘制结果',
        isDisable: false,
        callback: function (e) {
            saveResult();
        }
    }, {
        text: '设置区域颜色',
        isDisable: false,
        callback: function (e) {
            addGrid("fill",0);
        }
    }, {
        text: '删除网格区域',
        isDisable: false,
        callback: function (e) {
            deleteGrid();
        }
    }, {
        text: '查看点位坐标',
        isDisable: false,
        callback: function (e) {
            $.messager.alert('坐标位置',e.lng + "," + e.lat, 'info');
        }
    }];
    for (var i = 0; i < txtMenuItem.length; i++) {
        menu.addItem(new BMap.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback, 100));
    }
    map.addContextMenu(menu);

    loadAllGrid();
}

function loadAllGrid() {
    var area_id = $("#area_id");
    $.ajax({
        type: "GET",
        url: "/admin/getAllPoints",
        data: {},
        success: function (result) { 
            if (result.length > 0) {
                for (var i = 0; i < result.length; i++) {
                    if (result[i].lng_lat != null && result[i].lng_lat != "") {
                        var points = [];
                        var arr = result[i].lng_lat.split('|');
                        if (arr.length > 0) {
                            for (var j = 0; j < arr.length; j++) {
                                var xxyy = arr[j].split(',')
                                points.push(new BMap.Point(xxyy[0], xxyy[1]));
                            }
                        }
                        var color = result[i].color;
                        //创建面对象
                        polygon[i] = new BMap.Polygon(points, { strokeColor: color, strokeWeight: 1, strokeOpacity: 0.5, fillOpacity: 0.5, fillColor: color });
                        //向地图上添加面
                        map.addOverlay(polygon[i]);

                        polygon[i].area_id = result[i].area_id;

                        polygon[i].lng_lat = result[i].lng_lat;

                        polygon[i].area_name = result[i].area_name;

                    }
                    else {
                        var points = [];
                        points.push(new BMap.Point(0, 0));
                        polygon[i] = new BMap.Polygon(points, { strokeColor: "red", strokeWeight: 1, strokeOpacity: 0.5, fillOpacity: 0.5 });
                        polygon[i].area_id = result[i].area_id;
                        polygon[i].lng_lat = '0,0';
                        polygon[i].area_name = result[i].area_name;
                    }
                }
                addEvent(polygon);
            }
        },
        error: function()
        {
            $.messager.alert('系统提示', "请重新加载页面", "info");
        }
    });
}

function addEvent(polygon) {
    for (var i = 0; i < polygon.length; i++) {
        (function () {
            var current_polygon = polygon[i];
            current_polygon.addEventListener("mousedown", function () {
                clickPoint(current_polygon)
            });
        })();
        
    }
}
function clickPoint(polygon) {
    if (polygon.lng_lat != null && polygon.lng_lat != '') {
        var xxC = getCenterPoint("x", polygon.lng_lat);
        var yyC = getCenterPoint("y", polygon.lng_lat);
        if (xxC != 0 && yyC != 0) {
            var point = new BMap.Point(xxC, yyC);
            var opts = {
                width: 0,     // 信息窗口宽度
                height: 0     // 信息窗口高度
                //title: "", // 信息窗口标题
                //enableMessage: true,//设置允许信息窗发送短息
                //message: ""
            }
            infoWin = new BMap.InfoWindow(polygon.area_name, opts);  // 创建信息窗口对象
            map.openInfoWindow(infoWin, point); //开启信息窗口
        }
    }
}

//获取区域中心点坐标
function getCenterPoint(type, lng_lat) {
    var arrs = lng_lat.split('|');
    var Max = 0;
    var Min = 0;
    if (arrs.length > 0) {
        for (var j = 0; j < arrs.length; j++) {
            var xxyy = arrs[j].split(',')
            if (j == 0) {
                if (type == "x") {
                    Max = xxyy[0];
                    Min = xxyy[0];
                }
                else {
                    Max = xxyy[1];
                    Min = xxyy[1];
                }
            }
            else {
                if (type == "x") {
                    if (Min > xxyy[0]) {
                        Min = xxyy[0]
                    }
                    if (Max < xxyy[0]) {
                        Max = xxyy[0];
                    }
                }
                else {
                    if (Min > xxyy[1]) {
                        Min = xxyy[1]
                    }
                    if (Max < xxyy[1]) {
                        Max = xxyy[1];
                    }
                }
            }
        }
        return (Number(Min) + Number(Max)) / 2;
    }
    else {
        return 0;
    }
}

function addGrid(action,lng_lat) {
    var area_id = $("#area_id").val();
    if(area_id==0) {
        $.messager.alert('系统提示', "请选择社区!", "info");
        return false;
    }
    if (action == "add") {
        jQuery.ajax({
            type: "GET",
            url: "/admin/getPointsNum",
            data: "id="+area_id,
            success: function (result) {
                var points_num = result['points_num'];
                if (points_num > 0) {
                    $.messager.alert('系统提示', "该网格已经存在对应的区域面积，无法再次添加！", "info");
                }
                else {
                    if(polygon_new!==null) {
                        map.removeOverlay(polygon_new);
                    }
                    $('#dialog').dialog({
                        title: ('请选择网格颜色'),
                        iconCls: ('icon-tip'),
                        width: 250,
                        height: 240,
                        collapsible: false,//叠按钮
                        minimizable: false,//
                        maximizable: false,//最大化按钮
                        maximized: false,
                        closable: true,//关闭按钮。
                        closed: false,//关闭窗口。
                        draggable: true,//是否拖拽
                        resizable: true,//定义是否能够改变窗口大小。
                        modal: true,//窗体显示为模式化窗口。
                        onOpen: function () {
                            $('#picker').colpick({
                                flat: true,
                                layout: 'hex',
                                onSubmit: function (hsb, hex, rgb, el) {
                                    $('#area_color').val('#' + hex);
                                    closeDialog();
                                }
                            });
                        },
                        onClose: function () {
                            addPolygon(lng_lat);
                        }
                    });
                    $('#dialog').dialog("center");
                }
            }
        });
    }
    else {
        $('#dialog').dialog({
            title: ('请选择网格颜色'),
            iconCls: ('icon-tip'),
            width: 250,
            height: 240,
            collapsible: false,//叠按钮
            minimizable: false,//
            maximizable: false,//最大化按钮
            maximized: false,
            closable: true,//关闭按钮。
            closed: false,//关闭窗口。
            draggable: true,//是否拖拽
            resizable: true,//定义是否能够改变窗口大小。
            modal: true,//窗体显示为模式化窗口。
            onOpen: function () {
                $('#picker').colpick({
                    flat: true,
                    layout: 'hex',
                    onSubmit: function (hsb, hex, rgb, el) {
                        $('#area_color').val('#' + hex);
                        closeDialog();
                    }
                });
            },
            onClose: function () {
                var c = $('#area_color').val();
                var polygon_temp = getPolygon();
                polygon_temp.setStrokeColor(c);
                polygon_temp.setFillColor(c);
                $.messager.alert('系统提示', "设置颜色后需右键点击保存绘制结果保存！", "info");
            }
        });
        $('#dialog').dialog("center");
    }
}

function closeDialog() {
    $('#dialog').dialog("close");
}

function addPolygon(lng_lat) {
    var color = $('#area_color').val();
    var lng_lat = lng_lat.split(',');
    var points = [];
    points.push(new BMap.Point(lng_lat[0], lng_lat[1]));
    points.push(new BMap.Point(lng_lat[0], lng_lat[1]-0.008));
    points.push(new BMap.Point(lng_lat[0]-0.02, lng_lat[1]-0.008));
    points.push(new BMap.Point(lng_lat[0]-0.02, lng_lat[1]));
    //创建面对象
    polygon_new = new BMap.Polygon(points, { strokeColor: color, strokeWeight: 1, strokeOpacity: 0.5, fillOpacity: 0.5, fillColor: color });
    //向地图上添加面
    map.addOverlay(polygon_new);
    polygon_new.enableEditing();
}

function saveResult() {
    var area_id = $("#area_id").val();
    var area_name = $("#area_name").val();
    if(area_id==0) {
        $.messager.alert('系统提示', "请先选择相应的社区！", "info");
        return false;
    }
    var current_polygon = getPolygon();
    var color = current_polygon.getStrokeColor();
    //取面的边界坐标存到数据库
    var lnglats = current_polygon.getPath();
    var str_lnglat = "";
    if (lnglats.length > 0) {
        for (var i = 0; i < lnglats.length; i++) {
            str_lnglat += lnglats[i].lng + "," + lnglats[i].lat + "|";
        }
        if (str_lnglat != "") {
            str_lnglat = str_lnglat.substring(0, str_lnglat.length - 1);
        }
    }
    $.ajax({ 
        url: "/admin/addPoints", 
        dataType: "json",
        data:{area_id:area_id, lng_lat:str_lnglat, color:color},
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        type: "post",
        success: function(data){
            var status = data.status;
            if(status==1) {
                /*新增区域保存并添加事件*/
                if(current_polygon.is_new==1) {
                    saveSuccessEvent(current_polygon);
                }
                $.messager.alert('系统提示','保存成功!', 'info');
            } else {
                $.messager.alert('系统提示','保存失败!', 'info');
            }
        },
        error: function(){
            $.messager.alert('系统提示','出错了,请重新加载!', 'info');
        }
    });
}

function saveSuccessEvent(current_polygon)
{
    current_polygon.area_id = $("#area_id").val();
    current_polygon.area_name = $("#area_name").val();
    var lnglats = current_polygon.getPath();
    var str_lnglat = "";
    if (lnglats.length > 0) {
        for (var i = 0; i < lnglats.length; i++) {
            str_lnglat += lnglats[i].lng + "," + lnglats[i].lat + "|";
        }
        if (str_lnglat != "") {
            str_lnglat = str_lnglat.substring(0, str_lnglat.length - 1);
        }
    }
    current_polygon.lng_lat = str_lnglat;
    polygon.push(current_polygon);
    var tmp_arr = new Array();
    tmp_arr.push(current_polygon);
    addEvent(tmp_arr);
    polygon_new = null;
}

function deleteGrid() {
    var area_id = $("#area_id").val();
    if(area_id==0) {
        $.messager.alert('系统提示', "请先选择相应的社区！", "info");
        return false;
    }
    $.messager.confirm('删除确认', '您确定要删除该网格区域数据吗？', function (r) {
        if (r) {
            $.ajax({
                type: "POST",
                url: "/admin/deletePoints",
                data: {area_id:area_id},
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                success: function (result) {
                    var status = result.status;
                    if (status == 1) {
                        $.messager.alert('系统提示', "删除成功！", "info");
                        setTimeout(function () { window.location.reload(); }, 1000);
                    }
                    else {
                        $.messager.alert('系统提示', "删除失败！", "error");
                    }
                }
            });
        }
    });

}

function getPolygon() {
    var area_id = $("#area_id").val();
    var polygon_T = null;
    if (polygon_new == null) {
        for (var i = 0; i < polygon.length; i++) {
            if (polygon[i].area_id == area_id) {
                polygon_T = polygon[i];
            }
        }
        if(polygon_T!=null) {
            polygon_T.is_new = 0;
        }
    }
    else {
        polygon_T = polygon_new;
        polygon_T.is_new = 1;
    }
    return polygon_T;
}
function treeEvent()
{
    $(".easyui-tree").tree({
        onClick: function(node){
            var level = node.level;
            var area_id = node.area_id;
            var area_name = node.text;
            if(level==4) {
                $("#area_id").val(area_id);
                $("#area_name").val(area_name);
                /*社区可编辑*/
                var len = polygon.length;
                for(var i=0;i<len;i++) {
                    polygon[i].disableEditing();
                    if(area_id==polygon[i].area_id) {
                        polygon[i].enableEditing();
                    }
                }
                /*新增的社区设置为空*/
                map.removeOverlay(polygon_new);
                polygon_new = null;

            } else {
                $("#area_id").val('');
                $("#area_name").val('');
                /*社区可编辑*/
                var len = polygon.length;
                for(var i=0;i<len;i++) {
                    polygon[i].disableEditing();
                }
                map.removeOverlay(polygon_new);
                polygon_new = null;
            }
            
        },
        onExpand: function(node){
            
        }
    });
}